<template>
	<view class="alarm-detail">
		<!-- 详情卡片 -->
		<view class="detail-card">
			<view class="card-title">详情</view>
			<view class="detail-list">
				<view class="detail-item">
					<text class="item-label">状态</text>
					<text class="item-value">{{ getStatusText(alarmInfo.status) }}</text>
				</view>
				<view class="detail-item">
					<text class="item-label">类型</text>
					<text class="item-value">{{ alarmInfo.type }}</text>
				</view>
				<view class="detail-item">
					<text class="item-label">程度</text>
					<text class="item-value" :class="alarmInfo.severity ? 'severity-' + alarmInfo.severity : ''">
						{{ getSeverityText(alarmInfo.severity) }}
					</text>
				</view>
				<view class="detail-item">
					<text class="item-label">发起者</text>
					<text class="item-value">{{ alarmInfo.originatorName }}</text>
				</view>
				<view class="detail-item">
					<text class="item-label">开始时间</text>
					<text class="item-value">{{ formatTime(alarmInfo.startTs) }}</text>
				</view>
				<view class="detail-item">
					<text class="item-label">持续时间</text>
					<text class="item-value">{{ getDuration(alarmInfo.startTs) }}</text>
				</view>
			</view>
		</view>

		<!-- 分配卡片 -->
		<view class="assign-card">
			<view class="card-title">受托人</view>
			<view class="assign-content">
				<picker @change="onUserSelect" :value="selectedUserIndex" :range="userList" range-key="email">
					<view class="user-select">
						<view v-if="selectedUser" class="user-avatar">
							{{ selectedUser.email.charAt(0).toUpperCase() }}
						</view>
						<view v-else class="user-avatar default-avatar">
							<image src="/static/images/user.svg" mode="aspectFit"></image>
						</view>
						<text>{{ selectedUser ? selectedUser.email : '未分配' }}</text>
						<image src="/static/images/arrow-down.svg" mode="aspectFit" class="arrow-icon"></image>
					</view>
				</picker>
			</view>
		</view>

		<!-- 活动卡片 -->
		<view class="activity-card">
			<view class="card-title">活动</view>
			<view class="comment-input">
				<input 
					type="text" 
					v-model="comment"
					placeholder="请添加评论"
					class="input"
				/>
				<image 
					v-if="comment.trim()"
					src="/static/images/send.svg" 
					mode="aspectFit" 
					class="send-icon"
					@tap="addComment"
				></image>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<!-- 只在 ACTIVE_UNACK 状态下显示应答按钮 -->
			<button 
				v-if="alarmInfo.status === 'ACTIVE_UNACK'"
				class="btn acknowledge-btn" 
				@tap="acknowledgeAlarm"
			>应答</button>
			
			<!-- 在 ACTIVE_UNACK 或 ACTIVE_ACK 状态下显示清除按钮 -->
			<button 
				v-if="['ACTIVE_UNACK', 'ACTIVE_ACK'].includes(alarmInfo.status)"
				class="btn clear-btn" 
				@tap="clearAlarm"
			>清除</button>
		</view>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { formatTime } from '@/utils/timeUtils.js'
export default {
	data() {
		return {
			alarmId: '',
			alarmName: '',
			alarmInfo: {},
			userList: [],
			selectedUserIndex: -1,
			selectedUser: null,
			comment: ''
		}
	},

	onBackPress(options) {
		// 发送数据给上一页
		const eventChannel = this.getOpenerEventChannel();
  		eventChannel.emit('backToAlarmPage', {});
	},
	
	onLoad(options) {
		this.alarmId = options.id
		this.alarmName = decodeURIComponent(options.name)
		// 设置导航栏标题
		uni.setNavigationBarTitle({
			title: this.alarmName
		})
		this.fetchAlarmDetails()
		this.fetchAssignableUsers()  // 获取可分配的用户列表
	},
	
	methods: {
		async fetchAlarmDetails() {
			try {
				const result = await request.get(`/api/alarm/info/${this.alarmId}`)
				if (result) {
					this.alarmInfo = result
					
					// 更新选中的用户状态
					if (result.assignee) {
						this.selectedUser = result.assignee
						this.selectedUserIndex = this.userList.findIndex(user => 
							user.id.id === result.assignee.id.id
						)
					} else {
						// 如果没有受托人，选中"未分配"选项
						this.selectedUser = this.userList[0]  // "未分配"选项在第一位
						this.selectedUserIndex = 0
					}
				}
			} catch (error) {
				console.error('获取告警详情失败：', error)
				uni.showToast({
					title: '获取告警详情失败',
					icon: 'none'
				})
			}
		},
		
		// 移除本地的 formatTime 方法，改用导入的方法
		formatTime,
		
		// 计算持续时间
		getDuration(startTime) {
			const duration = Date.now() - startTime
			const days = Math.floor(duration / (24 * 60 * 60 * 1000))
			const hours = Math.floor((duration % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
			const minutes = Math.floor((duration % (60 * 60 * 1000)) / (60 * 1000))
			const seconds = Math.floor((duration % (60 * 1000)) / 1000)
			
			return `${days} 天 ${hours} 小时 ${minutes} 分钟 ${seconds} 秒`
		},
		
		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'ACTIVE_ACK': '激活已确认',
				'ACTIVE_UNACK': '激活未确认',
				'CLEARED_ACK': '清除已确认',
				'CLEARED_UNACK': '清除未确认'
			}
			return statusMap[status] || status
		},
		
		// 获取告警级别文本
		getSeverityText(severity) {
			if (!severity) return ''
			
			const severityMap = {
				'CRITICAL': '严重',
				'MAJOR': '重要',
				'MINOR': '次要',
				'WARNING': '警告',
				'INDETERMINATE': '未定'
			}
			return severityMap[severity] || severity
		},
		
		// 修改获取可分配的用户列表方法
		async fetchAssignableUsers() {
			try {
				const result = await request.get(
					`/api/users/assign/${this.alarmId}`,
					{
						pageSize: 50,
						page: 0,
						sortProperty: 'email',
						sortOrder: 'ASC'
					}
				)
				if (result && result.data) {
					// 添加默认的"未分配"选项
					const unassignedUser = {
						id: {
							entityType: 'USER',
							id: null
						},
						email: '未分配',
						firstName: null,
						lastName: null
					}
					this.userList = [unassignedUser, ...result.data]
				}
			} catch (error) {
				console.error('获取可分配用户列表失败：', error)
				uni.showToast({
					title: '获取用户列表失败',
					icon: 'none'
				})
			}
		},
		
		// 修改用户选择方法
		async onUserSelect(e) {
			try {
				this.selectedUserIndex = e.detail.value
				const selectedUser = this.userList[this.selectedUserIndex]
				console.log("selectedUser", selectedUser)

				// 选择的受托人就是当前的受托人，则不进行操作
				if(selectedUser.id.id != null && selectedUser.id.id === this.alarmInfo.assignee.id.id) {
					uni.showToast({
						title: '告警已经分配给此用户',
						icon: 'none'
					})
					return
				}

				if (selectedUser.id.id === null) {
					// 如果选择了"未分配"，调用删除分配的接口
					await request.delete(`/api/alarm/${this.alarmId}/assign`)
				} else {
					// 否则调用分配用户的接口
					await request.post(`/api/alarm/${this.alarmId}/assign/${selectedUser.id.id}`, this.alarmInfo)
				}

				// 显示成功提示
				uni.showToast({
					title: selectedUser.id.id === null ? '取消分配成功' : '分配成功',
					icon: 'success'
				})

				// 重新获取告警详情
				await this.fetchAlarmDetails()
				
				// 更新选中的用户状态
				this.selectedUser = selectedUser
				this.selectedUserIndex = this.userList.findIndex(user => 
					user.id.id === selectedUser.id.id
				)

			} catch (error) {
				console.error('操作失败：', error)
				uni.showToast({
					title: '操作失败',
					icon: 'none'
				})
			
				// 恢复之前的选择
				this.selectedUserIndex = this.userList.findIndex(user => 
					user.id.id === (this.alarmInfo.assignee?.id?.id ?? null)
				)
				this.selectedUser = this.alarmInfo.assignee
			}
		},
		
		// 修改添加评论方法
		async addComment() {
			if (!this.comment.trim()) return
			
			try {
				const commentData = {
					alarmId: {
						id: this.alarmId,
						entityType: 'ALARM'
					},
					type: 'OTHER',
					comment: {
						text: this.comment.trim()
					}
				}
				
				// 发送评论请求
				await request.post(`/api/alarm/${this.alarmId}/comment`, commentData)
				
				// 显示成功提示
				uni.showToast({
					title: '评论成功',
					icon: 'success'
				})
				
				// 清空输入框
				this.comment = ''
				
				// 刷新告警详情
				await this.fetchAlarmDetails()
				
			} catch (error) {
				console.error('发送评论失败：', error)
				uni.showToast({
					title: '发送评论失败',
					icon: 'none'
				})
			}
		},
		
		// 修改清除告警方法
		async clearAlarm() {
			try {
				// 发送清除请求
				await request.post(`/api/alarm/${this.alarmId}/clear`)
				
				// 显示成功提示
				uni.showToast({
					title: '清除成功',
					icon: 'success',
					complete: () => {
						// 延迟执行返回操作，让用户能看到提示
						setTimeout(() => {
							// 返回上一页
							uni.navigateBack({
								delta: 1
							})
						}, 1500)
					}
				})
				
			} catch (error) {
				console.error('清除失败：', error)
				uni.showToast({
					title: '清除失败',
					icon: 'none'
				})
			}
		},
		
		// 修改确认告警方法
		async acknowledgeAlarm() {
			try {
				// 发送应答请求
				await request.post(`/api/alarm/${this.alarmId}/ack`)
				
				// 显示成功提示
				uni.showToast({
					title: '应答成功',
					icon: 'success'
				})
				
				// 刷新告警详情
				await this.fetchAlarmDetails()
				
			} catch (error) {
				console.error('应答失败：', error)
				uni.showToast({
					title: '应答失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style>
.alarm-detail {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 20rpx;
}

.detail-card,
.assign-card,
.activity-card {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.card-title {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
	font-weight: 600;
}

.detail-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10rpx 0;
}

.item-label {
	color: #999;
	font-size: 28rpx;
}

.item-value {
	font-size: 28rpx;
	color: #333;  /* 默认颜色 */
}

.user-select {
	display: flex;
	align-items: center;
	gap: 16rpx;
	padding: 16rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
}

.user-avatar {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	background-color: #673ab7;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 28rpx;
	font-weight: 500;
}

.default-avatar {
	background-color: #f0f0f0;
	padding: 6rpx;
	box-sizing: border-box;
}

.default-avatar image {
	width: 100%;
	height: 100%;
	opacity: 0.7;
}

.arrow-icon {
	width: 28rpx;
	height: 28rpx;
	margin-left: auto;
}

.comment-input {
	display: flex;
	align-items: center;
	gap: 20rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 20rpx;
}

.input {
	flex: 1;
	font-size: 28rpx;
	padding-right: 20rpx;
}

.send-icon {
	width: 40rpx;
	height: 40rpx;
	padding: 10rpx;
	transition: opacity 0.3s;
}

.bottom-buttons {
	display: flex;
	gap: 20rpx;
	padding: 20rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
}

/* 当只有一个按钮时，让它占满宽度 */
.bottom-buttons .btn:only-child {
	flex: 1;
}

.btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 8rpx;
	font-size: 28rpx;
}

.clear-btn {
	background-color: #305680;
	color: #fff;
	border: none;
}

.acknowledge-btn {
	background-color: #fff;
	border: 1px solid #305680;
	color: #305680;
}

/* Severity 相关样式 */
.severity-CRITICAL { color: #FF0000; }
.severity-MAJOR { color: #FFA500; }
.severity-MINOR { color: #FFCA3D; }
.severity-WARNING { color: #ABAB00; }
.severity-INDETERMINATE { color: #008000; }
</style>
